package com.wwu.system.common.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wwu.common.constant.SecurityConst;
import com.wwu.common.web.ResultObj;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 账号并发登陆处理器
 * @author 一蓑烟雨
 * @version 1.0.0
 * @date 2023-07-26 09:21
 */
@Component
public class ConcurrentLoginHandler implements SessionInformationExpiredStrategy {
    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent sessionInformationExpiredEvent) throws IOException, ServletException {
        HttpServletResponse response = sessionInformationExpiredEvent.getResponse();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        ResultObj bean = ResultObj.except(SecurityConst.REPEAT_LOGIN);
        bean.setCode(HttpServletResponse.SC_CONFLICT);
        out.write(new ObjectMapper().writeValueAsString(bean));
        out.flush();
        out.close();
    }
}
